// 快乐数

package Leetcode;

import java.util.HashSet;
import java.util.Set;

class Solution202_1 {
    public boolean isHappy(int n) {
        Set<Integer> set = new HashSet<>();
        while (n != 1) {
            if (set.contains(n))
                return false;
            else
                set.add(n);

            int count = 0;
            while (n != 0) {
                count += (n % 10) * (n % 10);
                n /= 10;
            }
            n = count;

        }
        return true;
    }
}

class Solution202_2 {
    public boolean isHappy(int n) {
        int slow = n;
        int fast = next(n);
        while (slow != fast) {
            slow = next(slow);
            fast = next(next(fast));
        }
        return slow == 1 ? true : false;
    }

    public int next(int n) {
        int count = 0;
        while (n != 0) {
            count += (n % 10) * (n % 10);
            n /= 10;
        }
        return count;
    }
}